﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ZX.Web.UI.Controls;
using ZX.BLL.Extend;
using ZX.Common;
using ZX.BLL;
using ZX.DBModule;
using ZX.EHR.Library;
using ZX.TR.Library;
using ZX.TR.Bussiness;
using System.Text;
using System.Data;
using ZX.SYS.Bussiness.Message;
using ZX.SYS.Library;
using ZX.CRM.Library;
using ZX.CRM.Bussiness;
using System.Collections;
using ZX.DAL.DBExtend;
using System.Data.SqlClient;


namespace ZX.WebApp.Extend.AjaxData
{
    public partial class DataProcessin : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string action = this.GetStringFromQueryString("action", "");
            switch (action.ToLower())
            {
                case "get":
                    GetData();
                    break;
                case "save":
                    Save();
                    break;
                case "update":
                    Update();
                    break;
                case "delete":
                    Delete();
                    break;
                case "import":
                    Import();
                    break;
                case "cancel":
                    Cancel();
                    break;
                case "move":
                    Move();
                    break;
                case "movedept":
                    MoveDept();
                    break;
                case "copydept":
                    CopyDept();
                    break;
                case "clear":
                    Clear();
                    break;
                default:
                    GetData();
                    break;
            }
        }
        /// <summary>
        /// 一键清理
        /// </summary>
        private void Clear()
        {
            int iResult = 0;
            DbSql execsql = new DAL.DBExtend.DbSql();
            IDataParameter[] _Parameters = new IDataParameter[] { };
            SqlParameter UserID = new SqlParameter("@UserID", SqlDbType.UniqueIdentifier, 50);
            UserID.Direction = ParameterDirection.Input;
            UserID.Value = this.UserId;
            SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
            ReturnValue.Direction = ParameterDirection.Output;
            _Parameters = new IDataParameter[] { UserID,ReturnValue };
            if (execsql.RunProcedureReturnString("sp_clear", _Parameters, out iResult) == "1")
            {
                HttpContext.Current.Response.Write("1");
            }
            else
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        void MoveDept()
        {
            BDept dept = new BDept();
            if (dept.DeptMove(GetGuidFromQueryString("sourceID"), GetGuidFromQueryString("parentID")))
            {
                Response.Write("1");
            }
        }

        void CopyDept()
        {
            BDept dept = new BDept();
            if (dept.DeptCopy(GetGuidFromQueryString("sourceID")))
            {
                Response.Write("1");
            }

        }
        //移动
        private void Move()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            switch (strEntity.ToLower())
            {
                case "datdepartment":
                    //取消用户区域权限设置
                    moveDepartment();
                    break;
            }
        }
        //移动组织架构
        private void moveDepartment()
        {
            BaseBussnies bll = new BaseBussnies();
            //需要移动的部门ID集合
            string[] deptIds = ZXContext.Request.Form["jsonDataContent"].ToString().Split(',');
            //移动到部门
            string parentId = this.GetStringFromQueryString("parentId", "");
            string sql = "Exec sp_MoveDepartment '{0}','{1}'";
            sql = string.Format(sql, deptIds, parentId);
            try
            {
                bll.RunSqlCommand(sql);
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }

            //移动步骤
            //1:取出需要移动的部门
            //2:改变部门的上级单位(如果上级单位一起移动的话，则不修改)
            //3:生成新的部门路径 插入到数据库
            //4:将取出的部门的截止时间设为当前时间(标记为无效) 并将修改更新到数据库

            //IList<DatDepartment> _list = bll.GetEntitys<DatDepartment>(" deptName='" + deptName + "'");
            //   if (_list != null && _list.Count > 0)
            //   {
            //       HttpContext.Current.Response.Write("公司名已存在");
            //   }
            //   else
            //   {
            //       //先添加公司
            //       DatCompanyInfo companyinfo = new DatCompanyInfo();
            //       companyinfo.CompanyName = deptName;
            //       bll.entity = companyinfo;
            //       bll.Insert();

            //       DatDepartment dept = new DatDepartment();
            //       dept.DeptName = deptName;
            //       dept.AddUser = (Guid)this.UserId;
            //       dept.AddTime = DateTime.Now;
            //       dept.DeptPath = "@002";
            //       dept.IsOutDepartment = 1;
            //       bll.entity = dept;
            //       bll.Insert();
            //       HttpContext.Current.Response.Write("1");
        }
        private void Cancel()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            switch (strEntity.ToLower())
            {
                case "datemployee":
                    //取消用户区域权限设置
                    cancelAreaUserSet();
                    break;
            }
        }
        //取消用户区域权限设置
        private void cancelAreaUserSet()
        {
            try
            {
                string[] users = ZXContext.Request.Form["jsonUsers"].ToString().Split(',');
                BaseBussnies<DatEmployee> binstance = new BaseBussnies<DatEmployee>();
                DatEmployee employee = new DatEmployee();
                binstance.entity = employee;
                if (users.Length > 0)
                {
                    for (int i = 0; i < users.Length; i++)
                    {
                        employee = binstance.GetEntityById<DatEmployee>(Guid.Parse(users[i].ToString()));
                        employee.DeptIds = "";
                        binstance.Update(employee);

                    }

                }
                HttpContext.Current.Response.Write("1");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        //导出报表
        private void Import()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            string strCondition = this.GetStringFromQueryString("condition", "");
            string title = this.GetStringFromQueryString("title", "");
            strCondition = Server.UrlDecode(strCondition);
            BaseEntity entity = ZX.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            if (entity == null)
            {
                entity = ZX.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            }
            //得到要导出的数据源
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            DataTable dt = string.IsNullOrEmpty(strCondition) ? bll.GetDataTableByCondition("1=1") : bll.GetDataTableByCondition(strCondition);

            //得到要导出的字段名
            StringBuilder sbTitles = new StringBuilder();
            StringBuilder sbFields = new StringBuilder();
            BaseBussnies dtBll = new BaseBussnies();
            IList<DataListTemplate> _list = dtBll.GetEntitys<DataListTemplate>(" EntityName='" + strEntity + "'");
            _list = _list.OrderBy(p => p.iOrder).ToList();
            foreach (DataListTemplate _template in _list)
            {
                if (_template.THCaption.ToLower().IndexOf("id") == -1)
                {
                    sbTitles.Append(_template.THCaption + ",");
                    sbFields.Append(_template.Field + ",");
                }

            }
            string[] titles = sbTitles.ToString().TrimEnd(',').Split(',');
            string[] fields = sbFields.ToString().TrimEnd(',').Split(',');
            ExcelHelper eh = new ExcelHelper(titles, fields, dt);
            eh.DataToCSV(Server.UrlDecode(title));
        }

        /// <summary>
        /// 得到消息列表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private void GetMessageList()
        {

            string state = this.GetStringFromQueryString("state", "");
            if (state == "0" || state == "3")
            {
                //未查看
                BV_MessagePool messageMrg1 = new BV_MessagePool();
                int i = 0;
                if (state == "3")
                {
                    SYS.Library.V_MessagePool UnreadMessages = messageMrg1.GetNewestUnreadMessage(this.UserId);
                    if (UnreadMessages != null)
                    {
                        HttpContext.Current.Response.Write(UnreadMessages.MPoolID.ToString());
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("0");
                    }
                }
                else
                {
                    IList<SYS.Library.V_MessagePool> AllMessages = messageMrg1.GetUnreadSysMessages(this.UserId);
                    StringBuilder sb = new StringBuilder();

                    sb.Append("<table border='1px' cellspacing='0' cellpadding='0' width='100%' id='tb_messageList'>");
                    sb.Append("<thead>");
                    sb.Append("<tr>");
                    sb.Append("<th>消息类型</th><th>发送人</th><th>消息主题</th><th >发送时间</th>");
                    sb.Append("</tr>");
                    sb.Append("</thead>");
                    sb.Append("<tbody>");
                    if (AllMessages != null && AllMessages.Count > 0)
                    {
                        foreach (V_MessagePool message in AllMessages)
                        {
                            if (i % 2 != 0)
                            {
                                sb.Append("<tr class='odd' onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'odd');\"  onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");

                            }
                            else
                            {
                                sb.Append("<tr onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'');\" onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");
                            }
                            i++;
                            if (i > 8) continue;//只显示8条记录
                            string tds = "<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td>";

                            //显示消息类型
                            string type = "";
                            switch (message.MessageType)
                            {
                                case "0": type = "系统消息";
                                    break;
                                case "1": type = "Email";
                                    break;
                                case "2": type = "手机短信";
                                    break;
                                case "3": type = "QQ";
                                    break;
                            }
                            //显示时间
                            string dtStr = " <font color=\"#999999\">{0}</font>";
                            dtStr = String.Format(dtStr, message.SendTime.ToString("yyyy年MM月dd日"));
                            tds = string.Format(tds, type, message.AddUserName == "" ? "&nbsp&nbsp" : message.AddUserName, message.Title, dtStr);
                            sb.Append(tds);
                            sb.Append("</tr>");
                        }

                    }
                    else
                    {
                        sb.Append("<tr><td colspan=4 class='odd'>没有消息可显示</td></tr>");
                    }
                    sb.Append("</tbody>");
                    sb.Append("</table>");
                    HttpContext.Current.Response.Write(sb.ToString());
                }
            }
            else if (state == "1")
            {
                //已查看
                BV_HistoryMessagePool target = new BV_HistoryMessagePool(); // TODO: 初始化为适当的值
                IList<SYS.Library.V_HistoryMessagePool> ilist = target.GetReceiverSysMessages(this.UserId);
                StringBuilder sb = new StringBuilder();

                sb.Append("<table border='1px' cellspacing='0' cellpadding='0' width='100%' id='tb_messageList'>");
                sb.Append("<thead>");
                sb.Append("<tr>");
                sb.Append("<th>消息类型</th><th>发送人</th><th>消息主题</th><th >发送时间</th>");
                sb.Append("</tr>");
                sb.Append("</thead>");
                sb.Append("<tbody>");
                int i = 0;
                if (ilist != null && ilist.Count > 0)
                {
                    foreach (V_HistoryMessagePool message in ilist)
                    {
                        if (i % 2 != 0)
                        {
                            sb.Append("<tr class='odd' onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'odd');\"  onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");

                        }
                        else
                        {
                            sb.Append("<tr onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'');\" onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");
                        }
                        i++;
                        if (i > 8) continue;//只显示8条记录
                        string tds = "<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td>";

                        //显示消息类型
                        string type = "";
                        switch (message.MessageType)
                        {
                            case "0": type = "系统消息";
                                break;
                            case "1": type = "Email";
                                break;
                            case "2": type = "手机短信";
                                break;
                            case "3": type = "QQ";
                                break;
                        }
                        //显示时间
                        string dtStr = " <font color=\"#999999\">{0}</font>";
                        dtStr = String.Format(dtStr, message.SendTime.ToString("yyyy年MM月dd日"));
                        tds = string.Format(tds, type, message.AddUserName == "" ? "&nbsp&nbsp" : message.AddUserName, message.Title, dtStr);
                        sb.Append(tds);
                        sb.Append("</tr>");
                    }

                }
                else
                {
                    sb.Append("<tr><td colspan=4 class='odd'>没有消息可显示</td></tr>");
                }
                sb.Append("</tbody>");
                sb.Append("</table>");
                HttpContext.Current.Response.Write(sb.ToString());
            }
            else if (state == "")
            {
                //全部
                BV_AllMessage target = new BV_AllMessage(); // TODO: 初始化为适当的值
                IList<SYS.Library.V_AllMessage> ilist = target.GetAllSysMessages(this.UserId);
                StringBuilder sb = new StringBuilder();

                sb.Append("<table border='1px' cellspacing='0' cellpadding='0' width='100%' id='tb_messageList'>");
                sb.Append("<thead>");
                sb.Append("<tr>");
                sb.Append("<th>消息类型</th><th>发送人</th><th>消息主题</th><th >发送时间</th>");
                sb.Append("</tr>");
                sb.Append("</thead>");
                sb.Append("<tbody>");
                int i = 0;
                if (ilist != null && ilist.Count > 0)
                {
                    foreach (V_AllMessage message in ilist)
                    {
                        if (i % 2 != 0)
                        {
                            sb.Append("<tr class='odd' onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'odd');\"  onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");

                        }
                        else
                        {
                            sb.Append("<tr onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'');\" onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");
                        }
                        i++;
                        if (i > 8) continue;//只显示8条记录
                        string tds = "<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td>";

                        //显示消息类型
                        string type = "";
                        switch (message.MessageType)
                        {
                            case "0": type = "系统消息";
                                break;
                            case "1": type = "Email";
                                break;
                            case "2": type = "手机短信";
                                break;
                            case "3": type = "QQ";
                                break;
                        }
                        //显示时间
                        string dtStr = " <font color=\"#999999\">{0}</font>";
                        dtStr = String.Format(dtStr, message.SendTime.ToString("yyyy年MM月dd日"));
                        tds = string.Format(tds, type, message.AddUserName == "" ? "&nbsp&nbsp" : message.AddUserName, message.Title, dtStr);
                        sb.Append(tds);
                        sb.Append("</tr>");
                    }

                }
                else
                {
                    sb.Append("<tr><td colspan=4 class='odd'>没有消息可显示</td></tr>");
                }
                sb.Append("</tbody>");
                sb.Append("</table>");
                HttpContext.Current.Response.Write(sb.ToString());
            }

        }
        private void GetData()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            switch (strEntity)
            {
                case "V_HistoryMessagePool": GetMessageList();
                    break;
                case "EmployeePastTimeDepts": GetUserArea();
                    break;
                case "DatPost": GetDatPost();
                    break;
                case "V_UserEmp": GetDeptUser();
                    break;
                case "Announce": GetAnnounce();
                    break;
                case "hrAnnounce":
                    string type = this.GetStringFromQueryString("type", "0");
                    int intType = 0;
                    int.TryParse(type, out intType);
                    GetHrAnnounce(intType);
                    break;
                case "Birthday":
                    GetBirthday();
                    break;
                case "AllMessage": GetAllMessage();
                    break;
                case "CustomerNum":
                    getCustomerNum();
                    break;
                default: GetCommonData();
                    break;
            }



        }
        //得到本月，本日录入客户数量
        private void getCustomerNum()
        {

            int iResult = 0;
            IDataParameter[] _Parameters = new IDataParameter[] { };
            DbSql db = new DbSql();
            SqlParameter UserId = new SqlParameter("@UserId", SqlDbType.UniqueIdentifier, 50);
            UserId.Direction = ParameterDirection.Input;
            UserId.Value =this.UserId; //ID
           
            SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
            ReturnValue.Direction = ParameterDirection.Output; //返回值
            _Parameters = new IDataParameter[] { UserId, ReturnValue };
            string strSql = db.RunProcedureReturnString("sp_InPutCustomerNum", _Parameters, out iResult);
            
            HttpContext.Current.Response.Write(strSql);
        }
        //得到消息汇总
        private void GetAllMessage()
        {
            BaseBussnies bll = new BaseBussnies();
            //IList<V_Message> _list = bll.GetEntitys<V_Message>("AddUser='" + this.User.UserID + "' order by SendTime desc");
            IList<V_Message> _list = bll.GetEntitysBySqlComm<V_Message>("select top 6 * from V_Message where AddUser='" + this.User.UserID + "' order by SendTime desc");
            string htmlTemp = string.Empty;
            if (_list != null && _list.Count > 0)
            {
                int i = 0;
                htmlTemp = "<div style='width:100%;height:90%;overflow:auto;font-size: 12px;'>";
                htmlTemp += "   <table cellpadding='0' cellspacing='0' style='width:100%;' border='0'>";
                foreach (V_Message vm in _list)
                {
                    /*if (++i > 6)
                    {
                        sb.Append("<br>");
                        sb.Append("<img align='absMiddle' src='../../Images/arrow11.gif' width='9' height='9'>");
                        sb.Append(" <a href='#' onclick=\"javascript:fn_ShowMoreMessage()\" >查看更多...</a><br>");
                        break;//只显示6条记录 Extend/YUIList.aspx?entity=V_Message&functionID=3fa9d909-c7c1-4dae-91a7-be904d4d905e
                    }*/
                    //显示时间
                    string dtStr = " <font color=\"#999999\">{0}</font>";
                    dtStr = String.Format(dtStr, vm.SendTime.ToString("yyyy-MM-dd HH:mm"));

                    htmlTemp += "<tr style='height:30px;'><td style='border-bottom:1px dashed #ccc;'>";
                    htmlTemp += "   <img align='absMiddle' src='../../Images/arrow11.gif' width='9' height='9'>";
                    htmlTemp += " <a href='#' onclick=\"javascript:ShowAnnounce('" + vm.Title + "','" + vm.MPoolID.ToString() + "&Type=Mes" + "')\" >";
                    htmlTemp += Staple.PadString(vm.MsgContent, 12, true);
                    htmlTemp += "【" + vm.MessageType + "】";
                    htmlTemp += "   </a>";
                    htmlTemp += "   </td>";
                    htmlTemp += "<td style='text-align:right;border-bottom:1px dashed #ccc;'>" + dtStr + "&nbsp;</td>";
                    htmlTemp += "</tr>";
                }
                /*sb.Append("<br>");
                sb.Append("<img align='absMiddle' src='../../Images/arrow11.gif' width='9' height='9'>");
                sb.Append(" <a href='#' onclick=\"javascript:fn_ShowHistoryMessage()\" >查看历史消息...</a><br>");
                htmlTemp += sb.ToString();*/

                htmlTemp += "</table></div>";
            }
            HttpContext.Current.Response.Write(htmlTemp);
        }
        //得到公告
        private void GetAnnounce()
        {
            BaseBussnies bll = new BaseBussnies();
            BVuseremp buser = new BVuseremp();
            V_UserEmp user = buser.getUserInfoByUserId(this.UserId);
            //IList<Announce> _list = bll.GetEntitys<Announce>("1=1 order by AddTime desc");
            IList<Announce> _list = bll.GetEntitysBySqlComm<Announce>("select top 6 * from Announce order by AddTime desc");
            string htmlTemp = string.Empty;
            if (_list != null && _list.Count > 0)
            {
                htmlTemp = "<div style='width:100%;height:90%;overflow:auto;font-size: 12px;'>";
                htmlTemp += "   <table cellpadding='0' cellspacing='0' style='width:100%;' border='0'>";
                foreach (Announce announce in _list)
                {
                    //显示时间
                    string dtStr = " <font color=\"#999999\">{0}</font>";
                    dtStr = String.Format(dtStr, announce.AddTime.ToString("yyyy-MM-dd HH:mm"));
                    //显示是否置顶
                    string subject = announce.Subject;
                    string sendName = announce.AddUserName;
                    if (announce.IsOnTop)
                    {
                        //subject+="[置顶]";
                    }
                    htmlTemp += "<tr style='height:30px;'><td style='border-bottom:1px dashed #ccc;'>";
                    htmlTemp += "   <img align='absMiddle' src='../../Images/arrow11.gif' width='9' height='9'>";
                    htmlTemp += "   <a href='#' onclick=\"javascript:ShowAnnounce('" + announce.Subject + "','" + announce.ID.ToString() + "')\" >";
                    htmlTemp += Staple.PadString(subject, 12, true);
                    htmlTemp += "【" + announce.AddUserName + "】";
                    htmlTemp += "   </a>";
                    htmlTemp += "   </td>";
                    htmlTemp += "<td style='text-align:right;border-bottom:1px dashed #ccc;'>" + dtStr + "&nbsp;</td>";
                    htmlTemp += "</tr>";
                }
                htmlTemp += "</table></div>";
            }
            HttpContext.Current.Response.Write(htmlTemp);
        }

        //获取HR的消息数据
        /// <summary>
        /// 获取员工提醒数据
        /// </summary>
        /// <param name="type">类型0-获取前6条数据，1－获取更多数据</param>
        private void GetHrAnnounce(int type)
        {
            BaseBussnies bll = new BaseBussnies();
            //IList<DatMessageReceiver>
            IList<tmInformation> _list = bll.GetEntitys<tmInformation>("ClassType=1 order by AddTime Desc");
            //IList<tmInformation> _list = bll.GetEntitysBySqlComm<tmInformation>("select top 6 * from tmInformation where MessageType='h' and PushState='0' order by AddTime desc");
            string htmlTemp = string.Empty;
            int n = 0;
            if (_list != null && _list.Count > 0)
            {
                try
                {
                    htmlTemp = "<div style='width:100%;height:90%;overflow:auto;font-size: 12px;'>";
                    htmlTemp += "   <table cellpadding='0' cellspacing='0' style='width:100%;' border='0'>";
                    foreach (tmInformation announce in _list)
                    {
                        #region Modify:隐藏信息接收人过虑 By Yinlong 20141009
                        //IList<DatMessageReceiver> list_r = bll.GetEntitys<DatMessageReceiver>("MsgID='" + announce.MsgID + "'");
                        //if (list_r == null || list_r.Count == 0) continue;
                        //bool flag = false;
                        //foreach (DatMessageReceiver r in list_r)//判断当前用户是否在接收者列表中
                        //{
                        //    if (r.ReceiverID == this.User.EmpID || r.ReceiverID == Guid.Empty)//为公共消息时显示
                        //    {
                        //        flag = true;
                        //        break;
                        //    }
                        //}
                        //if (!flag)//当前用户不是接收者，不显示该条信息
                        //{
                        //    continue;
                        //} 
                        #endregion

                        //显示时间
                        string dtStr = " <font color=\"#999999\">{0}</font>";
                        dtStr = String.Format(dtStr, announce.AddTime.ToString("yyyy-MM-dd HH:mm"));
                        //显示是否置顶
                        string subject = announce.Title+"";

                        htmlTemp += "<tr style='height:30px;'><td style='border-bottom:1px dashed #ccc;'>";
                        htmlTemp += "   <img align='absMiddle' src='../../Images/arrow11.gif' width='9' height='9'>";
                        htmlTemp += "   <a href='#' onclick=\"javascript:ShowHrAnnounce('" + announce.Title + "','" + announce.ID.ToString() + "')\" >";
                        htmlTemp += Staple.PadString(subject, 15, true);
                        htmlTemp += "   </a>";
                        htmlTemp += "   </td>";
                        htmlTemp += "<td style='text-align:right;border-bottom:1px dashed #ccc;'>" + dtStr + "&nbsp;</td>";
                        htmlTemp += "</tr>";
                        n++;
                        if (n == 6 && type == 0) break;
                        if (n == 20 && type != 0) break;
                    }
                    htmlTemp += "</table></div>";
                }
                catch (Exception e)
                { }
            }
            HttpContext.Current.Response.Write(htmlTemp);
        }
        //获取生日的消息数据
        //得到公告
        private void GetBirthday()
        {
            BaseBussnies bll = new BaseBussnies();
            IList<DatMessageQueue> _list = bll.GetEntitys<DatMessageQueue>("MessageType='b' and PushState='0' order by AddTime desc");

            StringBuilder sb = new StringBuilder();
            string htmlTemp = string.Empty;
            if (_list != null && _list.Count > 0)
            {
                try
                {
                    htmlTemp = "<div style='width:100%;height:90%;overflow:auto;font-size: 12px;'>";
                    htmlTemp += "   <table cellpadding='0' cellspacing='0' style='width:100%;' border='0'>";
                    foreach (DatMessageQueue announce in _list)
                    {
                        IList<DatMessageReceiver> list_r = bll.GetEntitys<DatMessageReceiver>("MsgID='" + announce.MsgID + "'");
                        if (list_r == null || list_r.Count == 0) continue;
                        bool flag = false;
                        foreach (DatMessageReceiver r in list_r)//判断当前用户是否在接收者列表中
                        {
                            if (r.ReceiverID == this.User.EmpID || r.ReceiverID == Guid.Empty)//为公共消息时显示
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)//当前用户不是接收者，不显示该条信息
                        {
                            continue;
                        }
                        //if (++i > 10) continue;//只显示10条记录

                        //显示时间
                        string dtStr = " <font color=\"#999999\">{0}</font>";
                        dtStr = String.Format(dtStr, announce.AddTime.ToString("yyyy-MM-dd HH:mm"));
                        //显示是否置顶
                        string subject = announce.Title;

                        htmlTemp += "<tr style='height:30px;'><td style='border-bottom:1px dashed #ccc;'>";
                        htmlTemp += "   <img align='absMiddle' src='../../Images/arrow11.gif' width='9' height='9'>";
                        htmlTemp += " <a href='#' onclick=\"javascript:ShowBirthdayAnnounce('" + announce.Title + "','" + announce.MsgID.ToString() + "')\" >";
                        htmlTemp += Staple.PadString(subject, 30, true);
                        htmlTemp += "   </a>";
                        htmlTemp += "   </td>";
                        htmlTemp += "<td style='text-align:right;border-bottom:1px dashed #ccc;'>" + dtStr + "&nbsp;</td>";
                        htmlTemp += "</tr>";
                    }
                    htmlTemp += "</table></div>";
                }
                catch (Exception e)
                { }
            }
            HttpContext.Current.Response.Write(htmlTemp);
        }
        /// <summary>
        /// 设置HR消息pushstate，是否已读
        /// </summary>
        /// <param name="msgId">消息ID</param>
        private void SetHrAnnounce(string msgId)
        {
            try
            {
                BaseBussnies bll = new BaseBussnies();
                DatMessageQueue msg = bll.GetEntityByCondition<DatMessageQueue>("MsgID='" + msgId + "'") as DatMessageQueue;
                msg.PushState = "1";
                bll = new BaseBussnies(msg);
                bll.Update();
                HttpContext.Current.Response.Write("");
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write(e.Message);
            }
        }
        //
        private void GetDeptUser()
        {
            try
            {
                string deptId = this.GetStringFromQueryString("deptId", "");
                BaseBussnies bll = new BaseBussnies();
                IList<V_UserEmp> _list = bll.GetEntitys<V_UserEmp>("DeptID='" + deptId + "'");
                if (_list != null && _list.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (V_UserEmp userEmp in _list)
                    {
                        sb.Append(userEmp.UserID.ToString());
                        sb.Append(",");
                        sb.Append(userEmp.Name + " [" + userEmp.DeptName + "]");
                        sb.Append("~");
                    }
                    HttpContext.Current.Response.Write(sb.ToString());
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        private void GetUserArea()
        {
            try
            {
                //得到部门ID
                string empId = this.GetStringFromQueryString("EmpId", "");
                BaseBussnies bll = new BaseBussnies();
                BaseBussnies<DatDepartment> deptMgr = new BaseBussnies<DatDepartment>();
                IList<EmployeePastTimeDepts> pastTimes = bll.GetEntitys<EmployeePastTimeDepts>("EmpID='" + empId + "'");
                StringBuilder sb = new StringBuilder();
                if (pastTimes != null && pastTimes.Count > 0)
                {
                    DatDepartment dept = new DatDepartment();
                    deptMgr.entity = dept;
                    foreach (EmployeePastTimeDepts pastTime in pastTimes)
                    {
                        if (!string.Empty.Equals(pastTime.DeptID))
                        {
                            dept = deptMgr.GetEntityById<DatDepartment>(pastTime.DeptID);
                            if (dept != null)
                            {
                                sb.Append(dept.DeptID.ToString());
                                sb.Append(",");
                                sb.Append(dept.DeptName);
                                sb.Append("~");

                            }
                        }

                    }
                }
                HttpContext.Current.Response.Write(sb.ToString());
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        private void GetDatPost()
        {
            try
            {
                //得到部门ID
                string deptId = this.GetStringFromQueryString("deptId", "");
                BaseBussnies bll = new BaseBussnies();
                IList<DatPost> _list = bll.GetEntitys<DatPost>("DeptID='" + deptId + "'");
                if (_list != null && _list.Count > 0)
                {
                    DatPost de = _list[0];
                    HttpContext.Current.Response.Write(de.DeptID);
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        private void GetCommonData()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            string strCondition = this.GetStringFromQueryString("condition", "");
            strCondition = Server.UrlDecode(strCondition);
            BaseEntity entity = ZX.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            if (entity == null)
            {
                entity = ZX.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            }
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            IList<BaseEntity> list = string.IsNullOrEmpty(strCondition) ? bll.GetEntitysByCondition("1=1") : bll.GetEntitysByCondition(strCondition);
            if (list != null)
            {

                string strFormat = "{\"total\":" + list.Count().ToString() + ",\"rows\":[";
                string str = list.ToJSON().Replace("\n", "").Replace("\r", "").Replace("null", "");
                strFormat = strFormat + str + "]}";
                //strFormat = strFormat.Replace(new Regex("(^|[^\\\\])\\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\\"","$1new Date($2)");
                HttpContext.Current.Response.Write(strFormat);
            }
        }

        /// <summary>
        /// 保存用户角色
        /// </summary>
        private void Save()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            string ids = "";
            ids = this.GetStringFromQueryString("ids", "");
            if (strEntity == "SysRoleFunction")
            {
                ids = ZXContext.Request.Form[0].ToString();
            }
            string[] strIds = ids.Trim(',').Split(',');
            switch (strEntity)
            {
                case "SysUserRole":
                    SaveSysUserRole(strIds);
                    break;
                case "SysRoleFunction":
                    //SaveSysRoleFunction(strIds);
                    SaveSysRoleFunction(ids);
                    break;
                case "DatUser":
                    SavePassword(ids);
                    break;
                case "TrQuestionnaireSubject":
                    SaveTrQuestionnaireSubject(strIds);
                    break;
                case "CrmCustomerShare":
                    SaveShareCustomer(strIds);
                    break;
                case "SetPrivateNum":
                    SetPrivateNum(strIds);
                    break;
                case "TrActivityCourse":
                    SaveTrActivityCourse(strIds);
                    break;
                case "DatDepartment":
                    SaveDepartment();
                    break;
                case "TrSendQuestion":
                    SaveTrSendQuestion(strIds);
                    break;
                case "EmployeePastTimeDepts":
                    SaveEmployeeArea();
                    break;
                case "DatPost":
                    SaveDatPost(ids);
                    break;
                case "Announce":
                    SaveAnnounce();
                    break;
                case "hrAnnounce":
                    SetHrAnnounce(ids);
                    break;
                case "Set_UserDesktopItem":
                    SaveDeskTopItem();
                    break;


            }
        }
        //保存桌面设置
        private void SaveDeskTopItem()
        {
            string strJson = ZXContext.Request.Form["jsonDataContent"].Replace("[@@]", "\\");
            StringBuilder sSql = new StringBuilder("");
            ////保存设置之前删除之前的配置
            sSql.Append(string.Format("DELETE from SysUserDesktop where AddUser='{0}'\n", this.UserId));
            //获取新的配置信息
            var list = (List<DeskTopItemHelp>)Globals.JSonToObject<List<DeskTopItemHelp>>(strJson);
            string strSql1 = "insert into  SysUserDesktop values('{0}','{1}','{2}',{3},'{4}','{5}')\n";
            if (list != null)
            {
                foreach (var item in list)
                {

                    sSql.Append(string.Format(strSql1, Guid.NewGuid(), item.DesktopItemID, item.Region, item.sort, this.UserId.ToString(), DateTime.Now));
                }
            }
            BaseBussnies bll = new BaseBussnies();
            if (sSql.ToString() == "")
            {
                ZXContext.Response.Write("没有数据!");
                return;
            }
            int i = bll.RunSqlCommand(sSql.ToString());
            if (i > 0)
            {
                ZXContext.Response.Write("1");
            }
            else
            {
                //写日志
                WriteExpLog();
                ZXContext.Response.Write("0");
            }
        }
        private void SaveAnnounce()
        {
            try
            {

                string subject = ZXContext.Request.Form["txtSubject"].ToString();
                string files = ZXContext.Request.Files.Count.ToString();
                string ReceivedeptId = Request.QueryString["deptId"].ToString();
                string content = ZXContext.Request.Form["jsonDataContent"].ToString();
                ////业务处理类
                BaseBussnies Bbussness = new BaseBussnies();
                BVuseremp userMrg = new BVuseremp();
                int accLength = 0;
                // HttpFileCollection accfiles = ZXContext.Request.Files;
                //    if (accfiles.Count > 0)
                //    {
                //        for (int i = 0; i < accfiles.Count; i++)
                //        {
                //            HttpPostedFile accpostFile = accfiles[i];
                //            accLength += accpostFile.ContentLength;
                //            if (accLength > 5 * 1024 * 1024)
                //                ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script language='javascript'>alert('附件超过5M！')</script>");

                //            //return;
                //        }
                //    }
                //公告主体
                Announce announce = new Announce();
                V_UserEmp userInfo = userMrg.getUserInfoByUserId(this.UserId);
                announce.ID = Guid.NewGuid();
                announce.Subject = subject;
                announce.Content = content;
                announce.AddUser = (Guid)this.UserId;
                announce.AddTime = DateTime.Now;
                announce.SendDeptId = userInfo == null ? Guid.Empty : userInfo.DeptID;
                announce.AddUserName = this.User.UName;
                announce.IsOnTop = false;
                //公告接收部门
                AnnounceDepartment ad = new AnnounceDepartment();
                ad.AnnounceID = announce.ID;
                ad.DeptID = new Guid(ReceivedeptId);
                //添加附件
                Accessories access = new Accessories();
                access.ID = Guid.NewGuid();
                access.AccessoriesType = 1;
                access.Attach = null;
                access.Path = Server.MapPath("upload\\" + ZXContext.Request.Form["UpAccessoriesFileName"].ToString());
                access.Name = ZXContext.Request.Form["UpAccessoriesFileName"].ToString();
                AnnounceAccessories annouceA = new AnnounceAccessories();
                annouceA.AnnounceID = announce.ID;
                annouceA.AttachID = access.ID;
                Bbussness.Insert(announce);
                Bbussness.Insert(ad);
                Bbussness.Insert(access);
                Bbussness.Insert(annouceA);

                //    //#region 选择接收部门
                //    //string[] Depts = txt_AreaHidden1.Value.Split(',');
                //    //if (Depts.Length > 0 && Depts[0].Length == 36)
                //    //{
                //    //    foreach (string us in Depts)
                //    //    {
                //    //        if (us.Length != 36) continue;
                //    //        //InfoPlatDepartment dept=IDM.GetByID(new Guid(us));
                //    //        //if(dept!=null)
                //    //        //{
                //    //        ad = new AnnounceDepartment();
                //    //        ad.Announce = announce;
                //    //        ad.DepartmentID = new Guid(us);
                //    //        ad.SchoolID = SchoolID;
                //    //        //}
                //    //        //announce.Departments.Add(dept);
                //    //        announce.AnnounceDepartments.Add(ad);
                //    //    }
                //    //}




                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        private void SaveEmployeeArea()
        {
            try
            {
                string[] areaIds = ZXContext.Request.Form["jsonDataContent"].ToString().Split(',');
                string[] users = ZXContext.Request.Form["jsonUsers"].ToString().Split(',');
                System.Text.StringBuilder strSql = new StringBuilder();

                if (users.Length > 0)
                {
                    for (int i = 0; i < users.Length; i++)
                    {
                        strSql.Append("DELETE FROM EmployeePastTimeDepts where EmpID='" + users[i].ToString() + "'");
                        for (int j = 0; j < areaIds.Length; j++)
                        {
                            if (areaIds[j] != "")
                            {
                                strSql.Append("INSERT INTO EmployeePastTimeDepts Values('" + Guid.NewGuid() + "','" + users[i] + "','" + areaIds[j] + "','n')");
                            }
                        }

                    }
                }
                BaseBussnies bll = new BaseBussnies();
                if (strSql.ToString() == "")
                {
                    ZXContext.Response.Write("没有数据!");
                    return;
                }
                bll.RunSqlCommand(strSql.ToString());
                HttpContext.Current.Response.Write("1");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        private void SaveDatPost(string strIds)
        {
            BaseBussnies bll = new BaseBussnies();
            //获取部门下的所有职位
            try
            {
                string deptId = this.GetStringFromQueryString("deptId", "") == "" ? Guid.Empty.ToString() : this.GetStringFromQueryString("deptId", "");
                DatDepartment deptEntity = new DatDepartment();
                bll.entity = deptEntity;
                deptEntity = bll.GetEntityBySqlComm<DatDepartment>("select * from DatDepartment where deptid='" + deptId + "'");
                string[] s = strIds.Split(',');
                string strParent = this.GetStringFromQueryString("parentID", "") == "" ? Guid.Empty.ToString() : this.GetStringFromQueryString("parentID", "");
                for (int i = 0; i < s.Length; i++)
                {
                    DatPost dps = new DatPost();
                    dps.PositionID = new Guid(s[i]);     //职务ID
                    dps.DeptID = new Guid(deptId);
                    V_DatDutyInfo vdp = new V_DatDutyInfo();
                    bll.entity = vdp;
                    vdp = bll.GetEntityBySqlComm<V_DatDutyInfo>("select * from V_DatDutyInfo where Id='" + s[i] + "'");
                    dps.PostName = (vdp == null || deptEntity == null) ? "" : deptEntity.DeptName + vdp.Name;
                    dps.ParentID = new Guid(strParent);
                    dps.PostLevel = 1;
                    bll.entity = dps;
                    bll.Insert();
                }

                HttpContext.Current.Response.Write("1");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        private void SaveDepartment()
        {
            try
            {
                BaseBussnies bll = new BaseBussnies();
                string deptName = this.GetStringFromQueryString("deptName", "");
                IList<DatDepartment> _list = bll.GetEntitys<DatDepartment>(" deptName='" + deptName + "'");
                if (_list != null && _list.Count > 0)
                {
                    HttpContext.Current.Response.Write("公司名已存在");
                }
                else
                {
                    //先添加公司
                    DatCompanyInfo companyinfo = new DatCompanyInfo();
                    companyinfo.CompanyName = deptName;
                    bll.entity = companyinfo;
                    bll.Insert();

                    DatDepartment dept = new DatDepartment();
                    dept.DeptName = deptName;
                    dept.AddUser = (Guid)this.UserId;
                    dept.AddTime = DateTime.Now;
                    dept.DeptPath = "@002";
                    dept.IsOutDepartment = 1;
                    bll.entity = dept;
                    bll.Insert();
                    HttpContext.Current.Response.Write("1");
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("公司名已存在");
            }


        }
        /// <summary>
        /// 保存活动课程
        /// </summary>
        /// <param name="ids">课程ID列表</param>
        private void SaveTrActivityCourse(string[] Ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string[] point = new string[0];
            try
            {
                BaseBussnies bll = new BaseBussnies();
                TrActivityCourse tr = new TrActivityCourse();
                bll.entity = tr;
                bll.delete("TrActivityID='" + pid + "'");
                if (Ids.Length == 1 && Ids[0] == "null")
                {
                    this.ZXContext.Response.Write("1");
                    return;
                }
                else
                {
                    for (int i = 0; i < Ids.Length; i++)
                    {
                        string sql = string.Format("Exec sp_AddTrActivityCourse '{0}','{1}','{2}',{3}",
                                                 new Guid(pid), new Guid(Ids[i]), new Guid(), i);
                        bll.RunSqlCommand(sql);
                    }
                }
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }


        /// <summary>
        /// 保存用户角色
        /// </summary>
        /// <param name="ids">角色ID列表</param>
        private void SaveSysUserRole(string[] ids)
        {
            string userId = this.GetStringFromQueryString("id", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                SysUserRole sr = new SysUserRole();
                bll.entity = sr;
                bll.delete("UserID='" + userId + "'");
                if (ids.Length == 1 && ids[0] == "null")
                {
                    this.ZXContext.Response.Write("1");
                    return;
                }
                else
                {
                    foreach (string id in ids)
                    {
                        sr.RoleID = new Guid(id);
                        sr.UserID = new Guid(userId);
                        sr.Remark = DateTime.Now.ToShortDateString();
                        bll.Insert();
                    }
                }
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }
        //保存角色功能
        //private void SaveSysRoleFunction(string[] ids)
        private void SaveSysRoleFunction(string _id)
        {
            string[] ids = _id.TrimEnd(',').Split(',');
            string roldId = this.GetStringFromQueryString("roleid", "");
            string sql = "DELETE FROM SysRoleFunction Where RoleId='" + roldId + "' and  (not '" + _id + "' like '%'+cast(FunctionId as varchar(50))+'%') ";
            BaseBussnies bll = new BaseBussnies();
            SysRoleFunction sr = new SysRoleFunction();
            bll.entity = sr;
            bll.RunSqlCommand(sql);
            //bll.delete("RoleId ='" + roldId + "'");
            IList<SysRoleFunction> list = bll.GetEntitys<SysRoleFunction>("RoleId='" + roldId + "' and '" + _id + "' like '%'+cast(FunctionId as varchar(50))+'%'");
            if (!_id.Equals(""))
            {
                foreach (string id in ids)
                {

                    if (list == null)
                    {
                        sr.RoleID = new Guid(roldId);
                        sr.FunctionID = new Guid(id);
                        bll.Insert();
                    }
                    else
                    {
                        var _entity = list.Where(p => p.FunctionID == new Guid(id)).FirstOrDefault();
                        if (_entity == null)
                        {
                            sr.RoleID = new Guid(roldId);
                            sr.FunctionID = new Guid(id);
                            bll.Insert();
                        }
                    }
                }
            }
            HttpContext.Current.Response.Write("1");
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId">用户ID</param>
        private void SavePassword(string userId)
        {
            string oldPwd = this.GetStringFromQueryString("old", "");
            string newPwd = this.GetStringFromQueryString("news", "");
            BaseBussnies bll = new BaseBussnies();
            DatUser du = new DatUser();
            bll.entity = du;
            string sql = string.Format("select * from DatUser where UserID='{0}' and Password='{1}'", userId, ExtendMethods.GetMd5Hash(oldPwd));
            object obj = bll.GetEntityBySqlComm(sql);
            if (obj != null)
            {
                string sqlUpdate = string.Format("update DatUser set Password='{0}' where UserID='{1}'", ExtendMethods.GetMd5Hash(newPwd), userId);
                if (bll.RunSqlCommand(sqlUpdate) == 1)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("修改密码失败!");
                }
            }
            else
            {
                HttpContext.Current.Response.Write("0");  //原始密码输入错误!请重新输入!
            }
        }
        /// <summary>
        /// 保存私海客户数量设置
        /// </summary>
        /// <param name="Ids">用户ID集合</param>
        private void SetPrivateNum(string[] Ids)
        {
            int num = Int32.Parse(this.GetStringFromQueryString("num", ""));
            string[] point = new string[0];
            try
            {
                BaseBussnies bll = new BaseBussnies();
                CrmCustomerShare tr = new CrmCustomerShare();
                BCrmCustomerShare Bshare = new BCrmCustomerShare();
                DatUser du = (DatUser)System.Web.HttpContext.Current.Session["User"];
                if (du == null)
                {
                    this.ZXContext.Response.Write("获取用户ID有误!");
                    return;
                }
                string result = string.Empty;
                if (Ids.Length > 0)
                {
                    for (int j = 0; j < Ids.Length; j++)
                    {
                        if (Ids[j].Trim().Length == 0)
                        {
                            this.ZXContext.Response.Write(result);
                            return;
                        }
                        result = Bshare.ExecProcSetPrivateNum(new Guid(Ids[j].ToString()), du.UserID, num);
                    }
                    if (result.Trim() != "1")
                    {
                        this.ZXContext.Response.Write(result);
                        return;
                    }
                }
                this.ZXContext.Response.Write(result);
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }

        /// <summary>
        /// 保存共享客户
        /// </summary>
        /// <param name="Ids">题目ID集合</param>
        private void SaveShareCustomer(string[] Ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string toId = this.GetStringFromQueryString("toId", "");   //拥有客户的ID
            string strType = this.GetStringFromQueryString("type", "");  //类型 0：客户共享  1：客户分配时共享
            string[] point = new string[0];
            try
            {
                BaseBussnies bll = new BaseBussnies();
                CrmCustomerShare tr = new CrmCustomerShare();
                BCrmCustomerShare Bshare = new BCrmCustomerShare();
                DatUser du = (DatUser)System.Web.HttpContext.Current.Session["User"];
                if (du == null)
                {
                    this.ZXContext.Response.Write("获取用户ID有误!");
                    return;
                }
                string result = string.Empty;
                result = Bshare.ExecDeleteCrmProc(new Guid(pid), du.UserID);
                if (result != "1")
                {
                    this.ZXContext.Response.Write("删除用户共享信息有误!");
                    return;
                }
                if (Ids.Length > 0)
                {
                    if (Ids.Length == 2 && Ids[1] == "22")  //部门所有人保存
                    {
                        if (strType == "0")
                        {
                            result = Bshare.ExecProc(new Guid(pid), new Guid(toId), new Guid(Ids[0].ToString()), du.UserID, 2);
                        }
                        else
                        {
                            result = Bshare.ExecProcCustomerInfo(new Guid(pid), new Guid(toId), new Guid(Ids[0].ToString()), du.UserID, 2);
                        }
                    }
                    else   //逐个个人保存
                    {
                        for (int j = 0; j < Ids.Length; j++)
                        {
                            if (Ids[j].Trim().Length == 0)
                            {
                                this.ZXContext.Response.Write(result);
                                return;
                            }
                            if (strType == "0")
                            {
                                result = Bshare.ExecProc(new Guid(pid), new Guid(toId), new Guid(Ids[j].ToString()), du.UserID, 0);
                            }
                            else
                            {
                                result = Bshare.ExecProcCustomerInfo(new Guid(pid), new Guid(toId), new Guid(Ids[j].ToString()), du.UserID, 0);
                            }
                        }
                    }
                    if (result.Trim() != "1")
                    {
                        this.ZXContext.Response.Write(result);
                        return;

                    }
                }
                this.ZXContext.Response.Write(result);
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }

        /// <summary>
        /// 保存问卷题目表 (问卷选择题目)
        /// </summary>
        /// <param name="Ids">题目ID集合</param>
        private void SaveTrQuestionnaireSubject(string[] Ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string its = this.GetStringFromQueryString("its", "");
            string[] point = new string[0];
            try
            {
                BaseBussnies bll = new BaseBussnies();
                CrmCustomerShare tr = new CrmCustomerShare();
                bll.entity = tr;
                BTrQuestionnaireSubject bt = new BTrQuestionnaireSubject();
                IList<TrQuestionnaireSubject> list = bt.GetQuestionnaireSubjectInfoByQuestionnaireId(new Guid(pid));
                int listCount = 0;
                if (list != null)
                {
                    listCount = list.Count;

                }
                if (listCount >= int.Parse(its))
                {
                    this.ZXContext.Response.Write("问卷题目数已到达题目总数，不能再添加题目!");

                }
                else
                {
                    if (Ids.Length > int.Parse(its))
                    {
                        this.ZXContext.Response.Write("问卷题目数超过题目总数");
                    }
                    else
                    {
                        for (int j = 0; j < Ids.Length; j++)
                        {
                            DatUser du = (DatUser)System.Web.HttpContext.Current.Session["User"];
                            string sql = string.Format("Exec sp_AddQuestionniareSubject '{0}','{1}','{2}','{3}','{4}'",
                                                         new Guid(pid), new Guid(Ids[j]), 0, 'Y', du.UserID);
                            bll.RunSqlCommand(sql);
                        }
                        this.ZXContext.Response.Write("1");
                    }
                }
            }
            catch
            {
                this.ZXContext.Response.Write("");
            }
        }
        private void Update()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            string ids = this.GetStringFromQueryString("ids", "");
            string[] strIds = ids.Trim(',').Split(',');
            switch (strEntity.ToLower())
            {
                case "trindagatesubject":
                    UpdateTrIndagateSubject(strIds);
                    break;
                case "coursesum":
                    UpdateCourseSum();
                    break;
                case "datuser":
                    UserPwdSetting(strIds);
                    break;
                case "trquestionnaire":
                    UpdateQuestionniareSumup();
                    break;
                case "trquestionnairesubject":
                    UpdateQuestionnaireSubject(strIds);
                    break;
                case "crmmajorstudent":
                    UpdateCrmMajorStudent(strEntity);
                    break;
                case "v_crmmajorstudent":
                    SetManager();
                    break;
                case "v_crmmajorstudent1":
                    setSignIn();
                    break;
                case "crmmajorstudentexp5":
                    UpdateCrmMajorStudentExp5();
                    break;
                case "crmmajorstudentresetsignin":
                    ResetMajorStudentSignIn();
                    break;
                case "crmdelivermajorcopy":
                    UpdateCrmDeliverMajorCopy();
                    break;
            }
        }
        //签到
        private void setSignIn()
        {
            try
            {
                /*string pid = this.GetStringFromQueryString("id", ""); //学员ID
                ZX.BLL.Extend.BaseBussnies<CrmMajorStudent> bll = new ZX.BLL.Extend.BaseBussnies<CrmMajorStudent>();
                CrmMajorStudent newInstance = new CrmMajorStudent();
                bll.entity = newInstance;
                newInstance = bll.GetEntityById(pid) as CrmMajorStudent;
                newInstance.IsSignIn ="1";
                newInstance.SignIn = DateTime.Now;
                bll.Update(newInstance);*/

                int iResult = 0;
                IDataParameter[] _Parameters = new IDataParameter[] { };
                DbSql db = new DbSql();

                string id = this.GetStringFromQueryString("id", "");
                string[] str = id.Split(',');

                SqlParameter MajorStudentId = new SqlParameter("@MajorStudentId", SqlDbType.UniqueIdentifier, 50);
                MajorStudentId.Direction = ParameterDirection.Input;
                MajorStudentId.Value = str[0] == "" ? Guid.Empty : new Guid(str[0]); //学员ID
                SqlParameter MajorId = new SqlParameter("@MajorId", SqlDbType.UniqueIdentifier, 50);
                MajorId.Direction = ParameterDirection.Input;
                MajorId.Value = str[1] == "" ? Guid.Empty : new Guid(str[1]); ; //大课ID
                SqlParameter IsTrain = new SqlParameter("@IsTrain", SqlDbType.Char, 1);
                IsTrain.Direction = ParameterDirection.Input;
                IsTrain.Value = str[2]; //是否复训
                SqlParameter IsDecision = new SqlParameter("@IsDecision", SqlDbType.Char, 1);
                IsDecision.Direction = ParameterDirection.Input;
                IsDecision.Value = str[3]; //是否决策人
                SqlParameter CustomerId = new SqlParameter("@CustomerId", SqlDbType.UniqueIdentifier, 50);
                CustomerId.Direction = ParameterDirection.Input;
                CustomerId.Value = str[4] == "" ? Guid.Empty : new Guid(str[4]); ; //客户ID
                SqlParameter OrderProductId = new SqlParameter("@OrderProductId", SqlDbType.UniqueIdentifier, 50);
                OrderProductId.Direction = ParameterDirection.Input;
                OrderProductId.Value = str[5] == "" ? Guid.Empty : new Guid(str[5]); ; //订单产品ID
                SqlParameter AddUser = new SqlParameter("@Adduser", SqlDbType.UniqueIdentifier, 50);
                AddUser.Direction = ParameterDirection.Input;
                AddUser.Value = new Guid(this.UserId.ToString());
                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output; //返回值
                _Parameters = new IDataParameter[] { MajorId,MajorStudentId,IsTrain,IsDecision,
                                                     CustomerId,OrderProductId, AddUser, ReturnValue};
                string strSql = db.RunProcedureReturnString("sp_EditCrmDeliverMajorState", _Parameters, out iResult);
                if (strSql == "1")
                {
                    this.ZXContext.Response.Write("1");
                }
                else
                {
                    this.ZXContext.Response.Write(strSql);
                }
            }
            catch (Exception ex)
            {
                this.ZXContext.Response.Write(ex);
            }

        }
        //设置团长
        private void SetManager()
        {
            try
            {
                string pid = this.GetStringFromQueryString("id", "");
                ZX.BLL.Extend.BaseBussnies<CrmMajorStudent> bll = new ZX.BLL.Extend.BaseBussnies<CrmMajorStudent>();
                CrmMajorStudent newInstance = new CrmMajorStudent();
                bll.entity = newInstance;
                newInstance = bll.GetEntityById(pid) as CrmMajorStudent;
                //得到团号
                string GroupName = newInstance.GroupName;
                //根据团号找到该团的成员，并将其团长设置为当前选中学员
                List<CrmMajorStudent> list = (List<CrmMajorStudent>)bll.GetEntityListByCondition<CrmMajorStudent>("GroupName='" + GroupName + "'");
                if (list != null && list.Count > 0)
                {
                    foreach (CrmMajorStudent majorS in list)
                    {
                        majorS.Colonel = new Guid(pid);
                        bll.Update(majorS);
                    }
                }
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }

        }
        //更新大课学员
        private void UpdateCrmMajorStudent(string entityName)
        {
            try
            {
                string pid = this.GetStringFromQueryString("id", "");//学员ID
                string strJson = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");
                CrmMajorStudent instance = (CrmMajorStudent)Globals.JSONtoObject(entityName, strJson);
                ZX.BLL.Extend.BaseBussnies<CrmMajorStudent> bll = new ZX.BLL.Extend.BaseBussnies<CrmMajorStudent>();
                CrmMajorStudent newInstance = new CrmMajorStudent();
                bll.entity = newInstance;
                newInstance = bll.GetEntityById(pid) as CrmMajorStudent;

                newInstance.GroupNumber = instance.GroupNumber;     //顺序号
                if (instance.ClassName != "")
                    newInstance.ClassName = instance.ClassName;     //学员名    
                if (instance.PrintClassName != "")
                    newInstance.PrintClassName = instance.PrintClassName;//打印姓名
                if (instance.Exp4 != "")
                    newInstance.Exp4 = instance.Exp4;               //学员手机号
                if (instance.Post != "")
                    newInstance.Post = instance.Post;               //职位
                if (instance.Sex != "")
                    newInstance.Sex = instance.Sex;                 //性别
                if (instance.IDCard != "")
                    newInstance.IDCard = instance.IDCard;           //身份证号
                newInstance.GroupName = instance.GroupName;         //团号
                newInstance.Assistance = instance.Assistance;       //团长
                if (instance.IsDecision != "")
                    newInstance.IsDecision = instance.IsDecision;   //是否决策人
                if (instance.ActualHouseType.ToString() != "00000000-0000-0000-0000-000000000000")
                    newInstance.ActualHouseType = instance.ActualHouseType; //实际房型
                newInstance.Explain = instance.Explain;             //备注

                bll.Update(newInstance);
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }


        }

        public void UpdateCourseSum()
        {
            string pid = this.GetStringFromQueryString("id", "");
            string couseSum = this.GetStringFromQueryString("GroupName", "");
            //BaseBussnies bbls = new BaseBussnies();
            //string sql = "update TrActivityCourse set CourseSumary='" + CSVHelper.FmSQL(couseSum) + "' where TrActivityCourseID='" + CSVHelper.FmSQL(pid) + "'";
            //if (bbls.RunSqlCommand(sql) != 0)
            //{
            //    this.ZXContext.Response.Write("1");
            //}
            //else
            //{
            //    this.ZXContext.Response.Write("0");
            //}
        }
        /// <summary>
        /// 更新调研题目表和调研表中信息
        /// </summary>
        /// <param name="ids">题目ID集合</param>
        private void UpdateTrIndagateSubject(string[] ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string answer = this.GetStringFromQueryString("answer", "");
            string[] strAnswer = answer.Split('#');
            string point = this.GetStringFromQueryString("point", "");
            string[] strPoint = point.Split('#');
            string SumPoint = this.GetStringFromQueryString("sumpoint", "");
            string Result = this.GetStringFromQueryString("result", "");
            if (SumPoint == "")
            {
                SumPoint = "0";
            }
            try
            {
                BaseBussnies bll = new BaseBussnies();
                if (ids.Length == 1 && ids[0] == "")
                {
                    string sql = string.Format("Exec sp_UpdateIndagateSubject '{0}','{1}','{2}','{3}','{4}','{5}',{6}",
                                     new Guid(pid), new Guid("00000000-0000-0000-0000-000000000000"), strAnswer[0],
                                     0, Convert.ToDecimal(SumPoint), Result, 0);
                    if (bll.RunSqlCommand(sql) != 0)
                    {
                        this.ZXContext.Response.Write("1");
                    }
                    else
                    {
                        this.ZXContext.Response.Write("0");
                    }
                }
                else
                {
                    for (int i = 0; i < ids.Length; i++)
                    {
                        string GetPoint = "0";
                        if (strPoint[i + 1] == "")
                        {
                            GetPoint = "0";
                        }
                        else
                        {
                            GetPoint = strPoint[i + 1];
                        }
                        string sql = string.Format("Exec sp_UpdateIndagateSubject '{0}','{1}','{2}','{3}','{4}','{5}',{6}",
                                     new Guid(pid), new Guid(ids[i]), strAnswer[i + 1],
                                     Convert.ToDecimal(GetPoint), Convert.ToDecimal(SumPoint), Result, 1);
                        bll.RunSqlCommand(sql);
                    }
                    this.ZXContext.Response.Write("1");
                }
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }
        /// <summary>
        /// 管理员设置用户密码
        /// </summary>
        /// <param name="ids">用户ID</param>
        private void UserPwdSetting(string[] ids)
        {
            string pwd = this.GetStringFromQueryString("news", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                bll.entity = new DatUser();
                string strSql = string.Format("update DatUser set Password='{0}' where UserID='{1}'", ExtendMethods.GetMd5Hash(pwd), ids[0]);
                if (bll.RunSqlCommand(strSql) == 1)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        ///  更新问卷总结【】
        /// </summary>
        private void UpdateQuestionniareSumup()
        {
            string strId = this.GetStringFromQueryString("id", "");
            string QSumup = this.GetStringFromQueryString("sumup", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                bll.entity = new TrQuestionnaire();
                string strSql = string.Format("update TrQuestionnaire set QSumup='{0}' where TrQuestionnaireID='{1}'", QSumup, strId);
                if (bll.RunSqlCommand(strSql) == 1)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 更新问卷题目信息【】
        /// </summary>
        private void UpdateQuestionnaireSubject(string[] ids)
        {
            string strId = this.GetStringFromQueryString("id", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                bll.entity = new TrQuestionnaireSubject();
                string strSql = string.Format("update TrQuestionnaireSubject set Sequence='{0}',SubjectPoint='{1}',IsJumpOver='{2}' where TrQuestionnaireSubjectID='{3}'",
                                                ids[0], ids[1], ids[2], strId);
                if (bll.RunSqlCommand(strSql) == 1)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 发送问卷
        /// </summary>
        /// <param name="Ids"></param>
        private void SaveTrSendQuestion(string[] Ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string[] point = new string[0];
            try
            {
                BaseBussnies bll = new BaseBussnies();
                TrSendQuestion tr = new TrSendQuestion();
                bll.entity = tr;
                for (int j = 0; j < Ids.Length; j++)
                {
                    DatUser du = (DatUser)System.Web.HttpContext.Current.Session["User"];
                    string sql = "";
                    if (Ids.Length == 1 && Ids[0] == "11")  //集团所有人保存
                    {
                        sql = string.Format("Exec sp_AddSendQuestion '{0}','{1}','{2}',{3}",
                                                     new Guid(pid), "00000000-0000-0000-0000-000000000000", du.UserID, 1);
                    }
                    else if (Ids.Length == 1 && Ids[0] != "11")  //部门所有人保存
                    {
                        sql = string.Format("Exec sp_AddSendQuestion '{0}','{1}','{2}',{3}",
                                                     new Guid(pid), new Guid(Ids[0]), du.UserID, 2);
                    }
                    else   //逐个个人保存
                    {
                        sql = string.Format("Exec sp_AddSendQuestion '{0}','{1}','{2}',{3}",
                                                     new Guid(pid), new Guid(Ids[j]), du.UserID, 0);
                    }
                    bll.RunSqlCommand(sql);
                }
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }
        /// <summary>
        /// 学员改期
        /// </summary>
        private void UpdateCrmMajorStudentExp5()
        {
            try
            {
                string strId = this.GetStringFromQueryString("id", ""); //学员ID
                int iResult = 0;
                IDataParameter[] _Parameters = new IDataParameter[] { };
                DbSql db = new DbSql();
                SqlParameter MajorStudentId = new SqlParameter("@MajorStudentId", SqlDbType.UniqueIdentifier, 50);
                MajorStudentId.Direction = ParameterDirection.Input;
                MajorStudentId.Value = new Guid(strId);
                SqlParameter AddUser = new SqlParameter("@AddUser", SqlDbType.UniqueIdentifier, 50);
                AddUser.Direction = ParameterDirection.Input;
                AddUser.Value = new Guid(this.UserId.ToString());
                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output;
                _Parameters = new IDataParameter[] { MajorStudentId, AddUser, ReturnValue };
                string strSql = db.RunProcedureReturnString("sp_UpateCrmMajorStudentGaiQi", _Parameters, out iResult);
                if (strSql == "1")
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write(strSql);
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex);
            }
        }
        /// <summary>
        /// 学员取消签到
        /// </summary>
        private void ResetMajorStudentSignIn()
        {
            try
            {
                string strStudentId = this.GetStringFromQueryString("StudentId", "");
                string strOrderProductId = this.GetStringFromQueryString("OrderProductId", "");
                string strProductLayoutId = this.GetStringFromQueryString("ProductLayoutId", "");
                int iResult = 0;
                IDataParameter[] _Parameters = new IDataParameter[] { };
                DbSql db = new DbSql();
                SqlParameter MajorStudentId = new SqlParameter("@MajorStudentId", SqlDbType.UniqueIdentifier, 50);
                MajorStudentId.Direction = ParameterDirection.Input;
                MajorStudentId.Value = new Guid(strStudentId);
                SqlParameter OrderProductId = new SqlParameter("@OrderProductId", SqlDbType.UniqueIdentifier, 50);
                OrderProductId.Direction = ParameterDirection.Input;
                OrderProductId.Value = new Guid(strOrderProductId);
                SqlParameter ProductLayoutId = new SqlParameter("@ProductLayoutId", SqlDbType.UniqueIdentifier, 50);
                ProductLayoutId.Direction = ParameterDirection.Input;
                ProductLayoutId.Value = new Guid(strProductLayoutId);
                SqlParameter AddUser = new SqlParameter("@AddUser", SqlDbType.UniqueIdentifier, 50);
                AddUser.Direction = ParameterDirection.Input;
                AddUser.Value = new Guid(this.UserId.ToString());
                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output;
                _Parameters = new IDataParameter[] { MajorStudentId, OrderProductId, ProductLayoutId, AddUser, ReturnValue };
                string strSql = db.RunProcedureReturnString("sp_CrmMajorStudentResetSignIn", _Parameters, out iResult);
                if (strSql == "1")
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write(strSql);
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex);
            }
        }
        /// <summary>
        /// 大课交付单复制
        /// </summary>
        private void UpdateCrmDeliverMajorCopy()
        {
            try
            {
                //课程规划ID
                string strPid = this.GetStringFromQueryString("pid", "");
                string strProductLayoutId = strPid.Substring(0, strPid.Length - 1);
                //学员ID
                string strStudentId = this.GetStringFromQueryString("sid", "");
                int iResult = 0;
                IDataParameter[] _Parameters = new IDataParameter[] { };
                DbSql db = new DbSql();
                SqlParameter MajorStudentId = new SqlParameter("@MajorStudentId", SqlDbType.NVarChar, 8000);
                MajorStudentId.Direction = ParameterDirection.Input;
                MajorStudentId.Value = strStudentId;
                SqlParameter ProductLayoutId = new SqlParameter("@ProductLayoutId", SqlDbType.UniqueIdentifier, 50);
                ProductLayoutId.Direction = ParameterDirection.Input;
                ProductLayoutId.Value = new Guid(strProductLayoutId);
                SqlParameter AddUser = new SqlParameter("@AddUser", SqlDbType.UniqueIdentifier, 50);
                AddUser.Direction = ParameterDirection.Input;
                AddUser.Value = new Guid(this.UserId.ToString());
                SqlParameter ReturnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 50);
                ReturnValue.Direction = ParameterDirection.Output;
                _Parameters = new IDataParameter[] { MajorStudentId, ProductLayoutId, AddUser, ReturnValue };
                string strSql = db.RunProcedureReturnString("sp_EditCrmDeliverMajorCopy", _Parameters, out iResult);
                if (strSql == "1")
                {
                }
                else
                {
                    HttpContext.Current.Response.Write(strSql);
                    return;
                }
                HttpContext.Current.Response.Write("1");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex);
            }
        }

        private void Delete()
        {

        }
    }

    #region 桌面设置辅助类
    public class DeskTopItemHelp
    {
        //属性
        public int sort { get; set; }
        public Guid DesktopItemID { get; set; }
        public string Region { get; set; }
    }
    #endregion

    #region ExcelHelper
    /// <summary>
    /// 定义UI公用方法
    /// </summary>
    public class ExcelHelper
    {

        #region Fields
        string _fileName;
        DataTable _dataSource;//数据源
        string[] _titles = null;//列标题
        string[] _fields = null;//字段名

        #endregion

        #region .ctor
        /// <summary> 
        /// 构造函数 
        /// </summary> 
        /// <param name="dataSource">数据源</param> 
        public ExcelHelper()
        {

        }

        /// <summary> 
        /// 构造函数 
        /// </summary> 
        /// <param name="titles">要输出到 Excel 的列标题的数组</param> 
        /// <param name="fields">要输出到 Excel 的字段名称数组</param> 
        /// <param name="dataSource">数据源</param> 
        public ExcelHelper(string[] titles, string[] fields, DataTable dataSource)
            : this(titles, dataSource)
        {
            if (fields == null || fields.Length == 0)
                throw new ArgumentNullException("fields");
            if (titles.Length != fields.Length)
                throw new ArgumentException("titles.Length != fields.Length", "fields");

            _fields = fields;
        }

        /// <summary> 
        /// 构造函数 
        /// </summary> 
        /// <param name="titles">要输出到 Excel 的列标题的数组</param> 
        /// <param name="dataSource">数据源</param> 
        public ExcelHelper(string[] titles, DataTable dataSource)
            : this(dataSource)
        {
            if (titles == null || titles.Length == 0)
                throw new ArgumentNullException("titles");

            _titles = titles;
        }

        /// <summary> 
        /// 构造函数 
        /// </summary> 
        /// <param name="dataSource">数据源</param> 
        public ExcelHelper(DataTable dataSource)
        {
            if (dataSource == null)
                throw new ArgumentNullException("dataSource");
            // maybe more checks needed here (IEnumerable, IList, IListSource, ) ??? 
            // 很难判断，先简单的使用 DataTable 

            _dataSource = dataSource;
        }

        #endregion

        #region public Methods

        #region  导出到CSV文件并且提示下载
        /// <summary>
        /// 导出到CSV文件并且提示下载
        /// </summary>
        /// <param name="fileName"></param>
        public void DataToCSV(string fileName)
        {
            // 确保有一个合法的输出文件名 
            if (_fileName == null || _fileName == string.Empty || !(_fileName.ToLower().EndsWith(".xls")))
                _fileName = GetRandomFileName();
            string data = ExportCSV();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.BufferOutput = true;
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.csv", System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)));
            HttpContext.Current.Response.ContentType = "text/h323;charset=gbk";
            HttpContext.Current.Response.Write(data);
            HttpContext.Current.Response.End();
        }

        #endregion
        #endregion

        #region 返回写入CSV的字符串
        /// <summary>
        /// 返回写入CSV的字符串
        /// </summary>
        /// <returns></returns>
        private string ExportCSV()
        {
            if (_dataSource == null)
                throw new ArgumentNullException("dataSource");

            StringBuilder strbData = new StringBuilder();
            if (_titles == null)
            {
                //添加列名
                foreach (DataColumn column in _dataSource.Columns)
                {
                    strbData.Append(column.ColumnName + ",");
                }
                strbData.Append("\n");
                foreach (DataRow dr in _dataSource.Rows)
                {
                    for (int i = 0; i < _dataSource.Columns.Count; i++)
                    {
                        strbData.Append(dr[i].ToString() + ",");
                    }
                    strbData.Append("\n");
                }
                return strbData.ToString();
            }
            else
            {
                for (int j = 0; j < _titles.Length; j++)
                {
                    strbData.Append(_titles[j] + ",");
                }
                strbData.Append("\n");
                if (_fields == null)
                {
                    foreach (DataRow dr in _dataSource.Rows)
                    {
                        for (int i = 1; i < _dataSource.Columns.Count; i++)
                        {
                            strbData.Append(dr[i].ToString() + ",");
                        }
                        strbData.Append("\n");
                    }
                    return strbData.ToString();
                }
                else
                {
                    foreach (DataRow dr in _dataSource.Rows)
                    {
                        for (int i = 0; i < _fields.Length; i++)
                        {
                            strbData.Append(dr[_fields[i].ToString()].ToString() + ",");
                        }
                        strbData.Append("\n");
                    }
                    return strbData.ToString();
                }
            }
        }
        #endregion

        #region 得到一个随意的文件名
        /// <summary> 
        /// 得到一个随意的文件名 
        /// </summary> 
        /// <returns></returns> 
        private string GetRandomFileName()
        {
            Random rnd = new Random((int)(DateTime.Now.Ticks));
            string s = rnd.Next(Int32.MaxValue).ToString();
            return DateTime.Now.ToShortDateString() + "_" + s + ".csv";
        }
        #endregion
    }
    #endregion

    #region Staple
    public class Staple
    {
        #region 对齐字符串
        /// <summary>
        /// 对齐字符串
        /// </summary>
        /// <param name="src">字符串</param>
        /// <param name="sLen">对齐度</param>
        /// <returns></returns>
        public static string PadString(string src, int sLen)
        {
            if (src.Length >= sLen)
                return "<span title=\"" + src.Replace("\"", "“") + "\">" + src.Substring(0, sLen) + "...</span>";
            else
                return "<span title=\"" + src.Replace("\"", "“") + "\">" + src + "</span>";
        }

        /// <summary>
        /// 对齐字符串
        /// </summary>
        /// <param name="src">字符串</param>
        /// <param name="tipsrc">提示字符串</param>
        /// <param name="sLen">对齐度</param>
        /// <returns></returns>
        public static string PadString(string src, string tipsrc, int sLen)
        {
            if (src.Length >= sLen)
                return "<span title=\"" + tipsrc.Replace("\"", "“") + "\">" + src.Substring(0, sLen) + "...</span>";
            else
                return "<span title=\"" + tipsrc.Replace("\"", "“") + "\">" + src + "</span>";
        }

        /// <summary>
        /// 对齐字符串
        /// </summary>
        /// <param name="src">字符串</param>
        /// <param name="sLen">对齐度</param>
        /// <param name="sta">是否带tip提示</param>
        /// <returns></returns>
        public static string PadString(string src, int sLen, bool sta)
        {
            if (sta) return PadString(src, sLen);
            if (src.Length >= sLen)
                return src.Substring(0, sLen) + "...";
            else
                return src;
        }
        #endregion

        #region 解码
        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Decode(string str)
        {
            if (str == null) return "";
            str = str.Replace("%1", "<");
            str = str.Replace("%2", ">");
            str = str.Replace("%3", "\"");
            str = str.Replace("%4", "&");
            str = str.Replace("%5", "%");
            str = str.Replace("%6", " ");
            str = str.Replace("%7", ",");
            str = str.Replace("%8", "'");

            return str;
        }

        /// <summary>
        /// 编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Coding(string str)
        {
            if (str == null) return "";
            str = str.Replace("'", "%8");
            str = str.Replace(",", "%7");
            str = str.Replace(" ", "%6");
            str = str.Replace("%", "%5");
            str = str.Replace("&", "%4");
            str = str.Replace("\"", "%3");
            str = str.Replace(">", "%2");
            str = str.Replace("<", "%1");

            return str;
        }
        #endregion


        /// <summary>
        /// 显示姓名
        /// </summary>
        /// <param name="us"></param>
        /// <returns></returns>
        public static string ShowName(string Name)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<SPAN title='");
            sb.Append(Name);
            sb.Append("'");
            sb.Append(">");
            sb.Append(Name);
            sb.Append("</SPAN>");

            return sb.ToString();
        }
    }
    #endregion
}